package liziy.spring.beans.factory.config;

import liziy.spring.context.annotation.AnnotatedBeanDefintion;
import liziy.spring.core.AnnotationAttributes;
import liziy.spring.core.stereotype.Component;
import liziy.spring.core.stereotype.Repository;
import liziy.spring.core.stereotype.Service;

import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * @author Liziy
 * @date 2020/12/17 20:29
 **/
public class AnnotationBeanNameGenerator implements BeanNameGenerator {
    public static BeanNameGenerator INSTANCE = new AnnotationBeanNameGenerator();

    private AnnotationBeanNameGenerator() {

    }
    @Override
    public String buildBeanNameGenerator(BeanDefinition candidate) {
        if (candidate instanceof AnnotatedBeanDefintion) {
            AnnotatedBeanDefintion beanDefinition = (AnnotatedBeanDefintion) candidate;
            String beanName = determineAnnotationForBeanClassName(beanDefinition);
            if (null != beanName) {
                return beanName;
            }
        }
        //使用默认的别名生成方式
        return buildDefaultBeanName(candidate);
    }

    private String determineAnnotationForBeanClassName(AnnotatedBeanDefintion beanDefintion) {
        //获取当前处理这个BeanDefinition对象中对应类上面注解
        Class<? extends Annotation> annotationType
                = beanDefintion.getAnnotationMedata().getAnnotationType();
        Class<?> beanClass = beanDefintion.getBeanClass();
        String beanName = null;
        // 根据类提供的方法获取对应的注解对象
        Annotation annotation = beanClass.getAnnotation(annotationType);
        // 创建一个把注解对象转换成为属性集合对象
        AnnotationAttributes attributes = new AnnotationAttributes(annotation);
        Object value = attributes.get("value");
        if (value instanceof String) {
            String reVal = (String) value;
            if (!"".equals(reVal)) {
                beanName = reVal;
            }
        }

//        if (annotationType == Service.class) {
//            Service annotation = beanClass.getAnnotation(Service.class);
//            beanName = annotation.value();
//        } else if (annotationType == Repository.class) {
//            Repository annotation = beanClass.getAnnotation(Repository.class);
//            beanName = annotation.value();
//        } else if (annotationType == Component.class) {
//            Component annotation = beanClass.getAnnotation(Component.class);
//            beanName = annotation.value();
//        }
        return beanName;
    }

    /**
     * 将类的首字母小写
     * @param candidate
     * @return
     */
    private String buildDefaultBeanName(BeanDefinition candidate) {
        String simpleName = candidate.getBeanClass().getSimpleName();
        char[] chars = simpleName.toCharArray();
        char firstChar = chars[0];
        if (firstChar >= 'A' && firstChar <= 'Z') {
            chars[0] += 32;
        }
        return new String(chars);
    }
}
